package com.manager.ctroller;

import com.example.utils.Utils;
import org.apache.commons.dbutils.QueryRunner;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;

@WebServlet(name = "DelBatch", value = "/delBatch")
public class DelBatch extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String[] batchIds = request.getParameterValues("batchId");
        System.out.println("batchIds = " + Arrays.toString(batchIds));
        for (String value : batchIds) {
            delBatch(value);
            int i = delBatch(value);
            if (i > 0){
                System.out.println("删除了"+delNum+"条数据");
            }
        }
        response.sendRedirect("limit?page=1");
    }

    int delNum;
    /**
     * 批量删除
     *
     * @return int
     */
    private int delBatch(String delId) {
        QueryRunner queryRunner = new QueryRunner(Utils.getDataSource());
        try {
            int delete = queryRunner.update(
                    "delete from manager.person where id in (?)",
                    delId
            );
            delNum+=1;
            if (delete > 0) {
                System.out.println(delNum);
                return delete;
            } else {
                System.out.println("没删除 && 删除失败");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }
}
